package com.monolithiot.sso.schedule;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.service.AuthorizationService;
import com.monolithiot.sso.service.DeviceAuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 2018/12/14 Create by 郭文梁
 * AuthorizationSchedule
 * 授权相关定时调度器
 *
 * @author 郭文梁
 * @date 2018/12/14
 */
@Component
@Slf4j
public class AuthorizationSchedule {
    private final AuthorizationService authorizationService;
    private final DeviceAuthorizationService deviceAuthorizationService;

    @Autowired
    public AuthorizationSchedule(AuthorizationService authorizationService, DeviceAuthorizationService deviceAuthorizationService) {
        this.authorizationService = authorizationService;
        this.deviceAuthorizationService = deviceAuthorizationService;
    }

    /**
     * 定时删除数据库中过期的授权
     */
    @Scheduled(fixedRate = Constants.Auth.DEFAULT_OVERDUE_DELETE_PROCESS_RATE)
    public void deleteOverdueAuthorization() {
        int deleteCount = authorizationService.deleteOverdue();
        if (deleteCount > 0) {
            log.info("{} overdue authorization have bean deleted", deleteCount);
        }

        deleteCount = deviceAuthorizationService.deleteOverdue();
        if (deleteCount > 0) {
            log.info("{} overdue device authorization have bean deleted", deleteCount);
        }
    }
}
